package com.github.llyb120.testflow

class All{
    private final static ThreadLocal<LinkedList> local = new ThreadLocal<LinkedList>(){
        @Override
        protected LinkedList initialValue() {
            return new LinkedList()
        }
    }

    static Flow flow(Closure closure){
        def _flow = new Flow()
        pushStack(_flow)
        closure.call()
        popStack()
        return _flow
    }

    static Actor actor(Closure closure){
        def _actor = new Actor()
        def item = pickStack()
        if(item instanceof Flow){
            item.getActor().add(_actor)
        }
        pushStack(_actor)
        closure.call()
        popStack()
        return _actor
    }

    static Node node(Closure closure){
        def _node = new Node()
        def item = pickStack()
        if(item instanceof Flow){
            item.getNode().add(_node)
        }
        pushStack(_node)
        closure.call()
        popStack()
        return _node
    }

    static To to(Closure closure){
        def _to = new To()
        def item = pickStack()
        if(item instanceof Node){
            item.getTo().add(_to)
        }
        pushStack(_to)
        closure.call()
        popStack()
        return _to
    }

    static void name(String val){
        def item = pickStack()
        if(item instanceof Flow){
            item.setName(val)
        }
        if(item instanceof Actor){
            item.setName(val)
        }
        if(item instanceof Node){
            item.setName(val)
        }
    }

    static void define(String val){
        def item = pickStack()
        if(item instanceof Actor){
            item.getDefine().add(val)
        }
    }

    static void define(Closure val){
        def item = pickStack()
        if(item instanceof Actor){
            item.getDefine().add(val)
        }
    }

    static void who(String val){
        def item = pickStack()
        if(item instanceof Node){
            item.setWho(val)
        }
    }

    static void to(String val){
        def item = pickStack()
        if(item instanceof Node){
            item.getTo().add(val)
        }
    }

    static void which(String val){
        def item = pickStack()
        if(item instanceof To){
            item.setWhich(val)
        }
    }

    static void dynamic(Closure val){
        def item = pickStack()
        if(item instanceof To){
            item.setDynamic(val)
        }
    }

    private final static Object pickStack(){
        return local.get().getLast()
    }
    private final static Object pushStack(obj){
        local.get().addLast(obj)
    }
    private final static Object popStack(){
        return local.get().removeLast()
    }
}